var _newname = "";
$(function(){
    var _txtpresentation_val = "";
    var _mode = "";
    var _membre = "";
    var current_file = "";
    var _filename = "", editor;
	
    $("#cboseccion").change(function(){
        var _id = parseInt($(this).val())-2;
        document.location = './?ws=Sections&id='+ _id.toString()
    });

    /* JQUERY_EXTEND */
    $.extend({ 		
		
        // ADHESION
        initAdhesion : function(){
            editorTXT();
			
            $("#jqGrid").jqGrid({
                // <MODIFICAR>
                url: './Queries/query-adhesion.php?id='+_intUserSV+'nd='+new Date().getTime(),
                colNames:['int_id_adhesion', 'Titre', 'Lien', 'Etat'],
                colModel:[
                {
                    hidden:true, 
                    search:false, 
                    name:'int_id_adhesion', 
                    index:'int_id_adhesion', 
                    align:'left'
                },

                {
                    name:'var_title_link', 
                    index:'var_title_link', 
                    align:'left'
                },

                {
                    name:'var_link_pdfword', 
                    index:'var_link_pdfword', 
                    align:'left'
                },

                {
                    search:false, 
                    name:'var_htmldesc', 
                    index:'var_htmldesc', 
                    width:40, 
                    align:'left'
                }
                ],
                sortname: ['int_id_adhesion'],
                sortorder: "asc",
                width: 746,
                height: 200,
                // </MODIFICAR>
				
                loadtext: 'Chargement..',
                datatype: "json",
                pager: $('#jqpager'),
                rowNum:10,
                rowList:[10,20,50],	
                viewrecords: true,
                multiselect: true
            }); 
        }, 
        insertAdhesion : function(_var_title_link, _var_link_pdfword, _int_id_sections_view, _int_id_state){
			
            $.post("./?ws=Adhesion&act=insertAdhesion", {
                _var_title_link: _var_title_link, 
                _var_link_pdfword:_var_link_pdfword, 
                _int_id_sections_view:_int_id_sections_view, 
                _int_id_state:_int_id_state, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert($.trim(data));
                    $.modal.close();
                }
            });
        },
        updateAdhesion : function(_id, _var_title_link, _var_link_pdfword, _int_id_sections_view, _int_id_state){
            $.post("./?ws=Adhesion&act=updateAdhesion", {
                _id:_id, 
                _var_title_link: _var_title_link, 
                _var_link_pdfword:_var_link_pdfword, 
                _int_id_sections_view:_int_id_sections_view, 
                _int_id_state:_int_id_state, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert($.trim(data));
                    $.modal.close();
                }
                else $.modal.close();
            });
        },
        getAdhesion: function( _id ){
            $.post("./?ws=Adhesion&act=getAdhesion", {
                _id:_id, 
                cache:Math.random()
            }, function(data){
                if($.trim(data)!=""){
                    var _data = Array();
                    _data = data.split('_%_');
                    $('#txttitre').val( $.trim(_data[0]) ); 
                    $('#lbllien').html( $.trim(_data[1]) );
                    _newname = $.trim(_data[1]);
                    // $.getFilePath( _newname );
                    selectCbo( '#cboetat', $.trim( _data[2]) );	
                    iconError(false,"Document ajout&eacute;.");					
                    validateForm();
                }
            });
        },
        deleteAdhesion: function(_ids){
            $.post("./?ws=Adhesion&act=deleteAdhesion", {
                _ids:_ids, 
                cache:Math.random()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert(data);
                }
            });
        },
        getFilePath : function(_path){
            $.post("./?ws=Adhesion&act=getFilePath", {
                _path:_path, 
                _id: _intUserSV, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    $('#lbllien').html($.trim(data));	
                }
            });
        },
        uploadFile : function(_folder, _sizeLimit, _multi, photos){
            var current_file = "";
			
            $("#fileUpload").fileUpload({   
                uploader: './Resouces/js/uploader/uploader.swf',   
                cancelImg: './Resouces/js/uploader/cancel.png',   
                folder: _folder,   
                buttonText: 'Parcourir',
                checkScript: './Resouces/js/uploader/check.php',  
                width:110,
                height:35,
                fileDesc: "Format du document *.PDF uniquement",
                fileExt: '*.pdf',
				
                sizeLimit: _sizeLimit,
                script: './Resouces/js/uploader/upload.php',   
                multi: _multi,   
                simUploadLimit: 1, 
				
                onProgress: function(event,queueID,fileObj,data){
                    current_file = queueID;
                    $("#btn-save").attr("disabled","-1");
                },
                onSelect: function(event,queueID,fileObj){
                    $('#lbl-okfile').html('');
                    $('#lbllien').html('');
                },
                onSelectOnce: function(event,data){
                    $('#fileUpload').fileUploadStart();
                },
                onCancel: function(event,queueID,fileObj,data){
                    $("#btn-save").removeAttr("disabled");
                },
                onError: function(event,queueID,fileObj,errorObj){
                    $("#btn-save").removeAttr("disabled");
                },
                onComplete: function(event,queueID,fileObj,response,data){
                    $("#btn-save").removeAttr("disabled");					
                    _newname = fileObj.name;
                    iconError(false,"Document ajout&eacute;.");
                    $.getFilePath(_newname, _intUserSV);
                }
            }); 			
        },
        SaveAdhesion : function(_idSectionView,_txt_desc_adhesion){
            $.post("./?ws=Sections&act=SaveAdhesion", {
                id:_idSectionView, 
                _txt_desc_adhesion:_txt_desc_adhesion, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    alert(data);
                    $("#bnt-save-adhesion").removeAttr('disabled');
                }
                else{
                    $("#bnt-save-adhesion").removeAttr('disabled');
                }
            });
        }
    // END ADHESION

    });
    /* END JQUERY_EXTEND */
	
    function validateForm(){
        $('#txttitre').select();
        _form = $("#frm-adhesion").validate({
            event: "blur",
            rules:{ 
                'txttitre': "required",
                'cboetat': "required"	
            },
            messages:{
                'txttitre': "Entrez le titre du document.",
                'cboetat': "S&eacute;lectionnez l'&eacute;tat"
            }
        });	
		
        function disabledControls(val){
            if(val){
                $('#txttitre').attr('disabled','-1'); 
                $('#cboetat').attr('disabled','-1');
            }
            else{
                $('#txttitre').removeAttr('disabled'); 
                $('#cboetat').removeAttr('disabled');

                $("#btn-save").removeAttr('disabled');
            }
        }

        // SAVE FORM
        $("#frm-adhesion").submit(function(){
            if(_form.valid()){
                disabledControls(true);
				
                if(_mode == "update"){
                    if(_newname !=""){
                        $.updateAdhesion(_membre, $('#txttitre').val(), $('#lbllien').html(), _intUserSV, $('#cboetat').val() );
                    }
                    else{ 
                        iconError(true, "S&eacute;lectionnez une image!");
                        disabledControls(false);
                    }
                }
                else{
                    if(_newname ==""){
                        iconError(true,"S&eacute;lectionnez le document!");
                        disabledControls(false);
                    }
                    else{
                        $.insertAdhesion( $('#txttitre').val(), $('#lbllien').html(), _intUserSV, $('#cboetat').val() );
                    }
                }	
            }
			
            return false;
        });
    };
	
    function selectCbo(_idcbo, _intval){
        $(_idcbo+" option").each(function (){
            if($(this).val() == _intval){
                $(this).attr('selected','selected'); 
            }
        });
    }

    /*$("#get-Row").click( function(){
		var s = $("#jqGrid").getDataIDs();
		alert(s);
		$("#jqGrid").setSelection("2");
	});*/
	
    function iconError(_bool, _title){
        $('#lbl-okfile').css('display','none');
        var _icon = "";
        if(_bool) _icon = './Resouces/images/cancelfield.png';
        else _icon = './Resouces/images/okfield.png';
		
        $('#lbl-okfile').html('<img src="'+_icon+'" alt="'+_title+'" title="'+_title+'" />');
        $('#lbl-okfile').fadeIn();
    }
	
    function editorTXT(){
        new nicEditor({
            buttonList: [
            'bold','italic','underline','strikethrough','left','justify','link','unlink','removeformat'
            ],
            iconsPath: './Resouces/js/wysiwyg/nicEditorIcons.gif',
            maxHeight: 300
        }).panelInstance('txtadhesion',{
            hasPanel : true
        });

        editor = nicEditors.findEditor('txtadhesion');
    }
	
    $("#btn-cancel").click( function(){
        $.modal.close();
    });
    $("#bnt-save-adhesion").click( function(){
        $(this).attr('disabled','-1');
        $.SaveAdhesion(_intUserSV, editor.getContent());
    });
    $("#sinsert").click( function(){
        _mode = "insert";
        _filename = "";
        _newname = "";
		
        $('#Nouveau-title').html("Ajouter un document PDF"); 
        $("#Nouveau").modal({
            position: [0,0],
            opacity: 25,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                        $.uploadFile( '/csme.fr/adhesion', '15050000', false, false );
                        validateForm();
                    });
                });
            }			
        });
    });
	
    $("#supdate").click(function(){
        var s = $("#jqGrid").getGridParam('selarrrow');
        _filename = ""
        _mode = "update";
        _newname = "";
		
        $('#Nouveau-title').html("Modifier le document PDF");
        switch(s.length)
        {
            case 0:
                alert('Avertissement!\nS\u00E9lectionnez un document parmi la liste.');
                break;
			
            case 1:
                _membre = s[0];
                $.getAdhesion( _membre );
				
                $("#Nouveau").modal({
                    position: [0,0],
                    opacity: 45,
                    autoResize: true,
                    onOpen: function (dialog){
                        dialog.overlay.fadeIn('fast', function (){
                            dialog.container.fadeIn('fast', function (){
                                dialog.data.show();
                                $.uploadFile( '/csme.fr/adhesion', '15091456', false, false );
								
                                validateForm();
                            });
                        });
                    }			
                });
                break;
			
            default:
                alert('Avertissement\nS\u00E9lectionnez seulement un document \u00E0 la fois.');
                break;
        }
    });

    $("#sdelete").click(function(){
        if(_intUserT == 1){
            _mode = 'delete';
            var gr = $("#jqGrid").getGridParam('selrow');
	
            if( gr != null ) 
            {
                var s = $("#jqGrid").getGridParam('selarrrow');
                var f = s.toString();
                var j =  f.split(',');

                if(confirm("Eliminer document(s) PDF\nVous avez s\u00E9lectionner "+j.length+" document(s).\nVoulez vous vraiment l'effacer(s)?")){
                    $.deleteAdhesion(f);
                }
            }
            else{
                alert('Avertissement\nS\u00E9lectionnez les documents \u00E0 effacer.');
            }
        }
    });


    //Initializing
    $.initAdhesion();
    if(_sectSel!=0) selectCbo("#cboseccion",_sectSel); 

});